<template>
  <div class="add-form">
    <el-form :model="form" ref="form" :rules="rules" label-width="80px" size="normal">
      <el-row>
        <el-col :span="8" :offset="5">
          <el-form-item label="用户名" style="width:400px" prop="title">
            <el-input v-model="form.title" placeholder="请输入用户名"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" :offset="5">
          <el-form-item label="权限分配">
            <el-tree :data="treeList" show-checkbox :default-expand-all="false" node-key="id" ref="tree" highlight-current :props="defaultProps"></el-tree>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="transform: translateY(35px);">
        <el-col :span="8" :push="18">
          <el-form-item>
            <el-button @click="$emit('close')">取消</el-button>
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { list } from '@/api/base/menus'
import { add } from '@/api/base/permissions'
export default {
  name: 'usersAdd',
  data() {
    return {
      form: {
        title: '',
        permissions: []
      },
      rules: {
        title: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ]
      },
      treeList: [],
      defaultProps: {
        children: 'points',
        label: 'title'
      }
    }
  },

  created() {
    this.getTreeList()
  },
  methods: {
    async getTreeList() {
      let { data: res } = await list()
      this.treeList = res
      console.log(this.treeList)

      let obj = [
        {
          title: '系统菜单和页面权限点',
          id: 0,
          points: JSON.parse(JSON.stringify(this.treeList).replaceAll('childs', 'points'))
        }
      ]
      this.treeList = obj
    },
    async onSubmit() {
      //tree方法 若当前节点被勾选 则被选中的节点会返回一个数组
      let authChek = [...this.$refs.tree.getCheckedKeys()]
      let { data: res } = await add({
        title: this.form.title,
        permissions: authChek
      })

      this.$message.success('添加成功')
      this.$emit('close')
    }
  }
}
</script>

<style></style>
